﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebEntities;
using WebEntities.Models.WebInfo;

namespace com.subb.WebInformation
{
    public class WI_LeaveMsgReplyDAL
    {
        public WI_LeaveMsgReply GetReplyMsg(int replyId)
        {
            using (WebsiteDbEntities ctx = new WebsiteDbEntities())
            {
                ctx.ContextOptions.LazyLoadingEnabled = false;
                WI_LeaveMsgReply reply = ctx.WI_LeaveMsgReply.SingleOrDefault(c => c.ReplyID == replyId);
                return reply;
            }
        }

        public WI_LeaveMsgReply GetReplyMsgByMsgID(int msgId)
        {
            using (WebsiteDbEntities ctx = new WebsiteDbEntities())
            {
                ctx.ContextOptions.LazyLoadingEnabled = false;
                WI_LeaveMsgReply reply = ctx.WI_LeaveMsgReply.FirstOrDefault(c => c.MsgID == msgId);
                return reply;
            }
        }

        /// <summary>
        /// 创建或更新回复信息。
        /// </summary>
        /// <param name="msgId">留言信息ID</param>
        /// <returns>0：没有找到留言信息；1：创建回复信息；2：更新回复信息。</returns>
        public int SaveReplyMsg(int msgId, ReplyMsg v_reply)
        {
            int result = 0;
            using (WebsiteDbEntities ctx = new WebsiteDbEntities())
            {
                WI_LeaveMsg lmsg = ctx.WI_LeaveMsg.SingleOrDefault(c => c.MsgID == msgId);
                if (lmsg != null)
                {
                    lmsg.IsReply = true;
                    WI_LeaveMsgReply reply = ctx.WI_LeaveMsgReply.FirstOrDefault(c => c.MsgID == msgId);
                    if (reply == null)
                    {
                        WI_LeaveMsgReply wireply = new WI_LeaveMsgReply
                        {
                            MsgID = v_reply.MsgID,
                            ReplyContent = v_reply.ReplyContent,
                            ReplyMan = v_reply.ReplyMan,
                            CreateTime = DateTime.Now,
                            Creator = v_reply.Creator
                        };
                        ctx.WI_LeaveMsgReply.AddObject(wireply);
                        result = 1;
                    }
                    else
                    {
                        reply.ReplyContent = v_reply.ReplyContent;
                        reply.ReplyMan = v_reply.ReplyMan;
                        result = 2;
                    }
                }
                ctx.SaveChanges();
            }
            return result;
        }
    }
}
